package com.jcl.recruit.api.wechat.controller;

import com.jcl.core.resp.ApiResponse;
import com.jcl.core.security.ShareUserToken;
import com.jcl.core.utils.StringUtils;
import com.jcl.recruit.resume.service.ResumeShareService;
import com.jcl.recruit.wechat.service.WechatService;
import com.jcl.recruit.wechat.utils.WechatUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/wechat")
public class WechatController {

    private static final Logger logger = LoggerFactory.getLogger(WechatController.class);

    private static final String token = "jucailin";

    @Autowired
    private WechatService wechatService;
    @Autowired
    private ResumeShareService resumeShareService;

    @RequestMapping("/share/register/inviteurl")
    public ApiResponse shareInviteUserUrl() {
        Map<String, Object> data = wechatService.inviteUser();
        return ApiResponse.success(data);
    }

    @Deprecated
    @RequestMapping("/share/resume")
    public ApiResponse shareResume(String id, String fromType) {
        if (StringUtils.isEmpty(id) || null == fromType) {
            return ApiResponse.error("请求简历参数不能为空！");
        }
        Map<String, Object> data = resumeShareService.getShareResume(Integer.parseInt(id), fromType);
        return ApiResponse.success(data);
    }

    @Deprecated
    @RequestMapping("/share/resume/callback")
    public ApiResponse shareResumeCallback(String id, String fromType) {
        if (StringUtils.isEmpty(id) || null == fromType) {
            return ApiResponse.error("请求简历参数不能为空！");
        }
        int number = resumeShareService.callbackShareResume(Integer.parseInt(id), fromType);
        return ApiResponse.success("OK");
    }

    @RequestMapping("/share/resume/detail")
    public ApiResponse shareResumeDetail(String token) {
        if (StringUtils.isEmpty(token)) {
            return ApiResponse.error("请求简历参数不能为空！");
        }
        ShareUserToken tokenInfo = null;
        try {
            tokenInfo = ShareUserToken.decodeResumeToken(token);
        } catch (Exception e) {
            return ApiResponse.error("非法请求！");
        }

        Map<String, Object> data =
                resumeShareService.getShareResumeDetail(Integer.parseInt(tokenInfo.getResumeId()), tokenInfo.getFromType());
        if (null == data) {
            return ApiResponse.error("当前简历不存在！");
        }
        return ApiResponse.success(data);
    }

    @RequestMapping("/signature")
    public ApiResponse signature(String currentUrl) {
        if (StringUtils.isEmpty(currentUrl)) {
            return ApiResponse.error("当前路径参数不能为空！");
        }
        logger.info("signature url is : {}", currentUrl);
        WechatUtils.SignatureInfo info = wechatService.getSignature(currentUrl);
        return ApiResponse.success(info);
    }

    @RequestMapping
    public void access(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String signature = req.getParameter("signature");
        // 时间戳
        String timestamp = req.getParameter("timestamp");
        // 随机数
        String nonce = req.getParameter("nonce");
        // 随机字符串
        String echostr = req.getParameter("echostr");

        List<String> list = new ArrayList<String>();
        list.add(nonce);
        list.add(timestamp);
        list.add(token);

        Collections.sort(list);

        PrintWriter out = null;
        try {
            out = resp.getWriter();
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
            if (DigestUtils.shaHex(list.get(0) + list.get(1) + list.get(2)).equals(signature)) {
                out.print(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
            out = null;
        }

    }

}
